/**
 * @description demo
<template>
   <button v-longhandle:[2000]="longpress">按钮</button>
   <button v-longhandle:2000="longpress">按钮</button>

</template>

<script setup>
const longpress = () => {
  console.log('时间')
}
</script>
 */

import type { DirectiveBinding } from 'vue'
// 在项目的某个 TypeScript 文件中定义（例如：types.d.ts）
declare global {
  interface HTMLElement {
    $duration?: number
  }
}
const longpress = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const cb = binding.value
    const $duration = Number(binding.arg) || 1000 // 获取长按时长, 默认3秒执行长按事件
    if (typeof cb !== 'function') return console.warn('v-longpress指令必须接收一个回调函数')
    let timer: NodeJS.Timeout | null = null
    const add = (e: MouseEvent | TouchEvent) => {
      // 排除点击与右键情况, event.button: 0-左键  2-右键
      if (e.type === 'click' && ('button' in e) && e.button !== 0) return
      e.preventDefault()
      if (timer === null) {
        timer = setTimeout(() => {
          cb()
          timer = null
        }, $duration)
      }
    }
    const cancel = () => {
      if (timer !== null) {
        clearTimeout(timer)
        timer = null
      }
    }

    // 添加计时器
    el.addEventListener('mousedown', add)
    el.addEventListener('touchstart', add)
    // 取消计时器
    el.addEventListener('click', cancel)
    el.addEventListener('mouseout', cancel)
    el.addEventListener('touchend', cancel)
    el.addEventListener('touchcancel', cancel)
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    // 可以实时更新时长
    el.$duration = Number(binding.arg)
  },
  unmounted(el: HTMLElement) {
    el.removeEventListener('mousedown', () => { })
    el.removeEventListener('touchstart', () => { })
    el.removeEventListener('click', () => { })
    el.removeEventListener('mouseout', () => { })
    el.removeEventListener('touchend', () => { })
    el.removeEventListener('touchcancel', () => { })
  }
}

export default longpress
